package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务端...");
            socket=new Socket("localhost",8085);
            System.out.println("服务端连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            Serverhandler handle=new Serverhandler();
            Thread t=new Thread(handle);
            t.start();

            OutputStream out=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(out);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);

            Scanner scan=new Scanner(System.in);
            while(true){
                System.out.println("请输入昵称：");
                String nickName=scan.nextLine();
                if (nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空");
                }else {
                    pw.println(nickName);
                    break;
                }
            }


            while (true){
                String line=scan.nextLine();
                if ("exit".equalsIgnoreCase(line)) {
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }
    private class Serverhandler implements Runnable{
        public void run(){
            try {
                //通过socket获取输入流用于读取服务端发送过来的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while((message=br.readLine())!=null){
                    System.out.println(message); //将服务端发送来的消息输出
                }
            } catch (IOException e) {
            }
                }
            }

        }

